from wsgiref.simple_server import make_server
import wsgiref.util
import os

import MSConfig; MSConfig.init('.')
import MSLogger2; log = MSLogger2.configure('wsgi_server')
import MSDatabase
import MSWSGIPatterns as w
import MSMethods

# PAGES
def handle_page(data): return w.getHead() + data + w.getFoot()

def handle_textload(contenttype, environ, start_response):
    name    = wsgiref.util.shift_path_info(environ)
    if not w.checkName(name): 
        log.info('handle_textload: 404 on name %s', name)
        return w.get404(start_response, name)
    fname   = MSConfig.config.get('main', contenttype) + name
    if not w.checkFile(fname):
        log.info('handle_textload: 404 on file %s', fname)
        return w.get404(start_response, name)

    f = open(fname, 'r')
    w.putHeader(start_response, 200, contenttype)
    return [f.read()]
def handle_imageload(contenttype, environ, start_response):
    name    = wsgiref.util.shift_path_info(environ)
    if not w.checkName(name): 
        log.info('handle_imageload: 404 on name %s', name)
        return w.get404(start_response, name)
    fname   = MSConfig.config.get('main', contenttype) + name
    if not w.checkFile(fname): 
        log.info('handle_imageload: 404 on file %s', fname)
        return w.get404(start_response, name)
    spl = fname.split('.')
    ext = spl[len(spl) - 1]
    if len(spl) == 0 or len(ext) == 0:
        log.info('handle_imageload: 404 on file ext %s', fname)
        return w.get404(start_response, name)

    f = open(fname, 'r')
    w.putHeader(start_response, 200, ext, contenttype)
    return [f.read()]


# APPLICATION
def myapp(environ, start_response):
    rqtype = wsgiref.util.shift_path_info(environ)

    if rqtype == 'method':
        return handle_page(MSMethods.handle_method(environ, start_response))
    if rqtype == 'rawmethod':
        return MSMethods.handle_method(environ, start_response)
    if rqtype == 'html':
        return handle_page(handle_textload(rqtype, environ, start_response))
    if rqtype in ['css', 'js']:
        return handle_textload(rqtype, environ, start_response)
    if rqtype == 'image':
        return handle_imageload(rqtype, environ, start_response)


    return handle_page(w.get404(start_response, rqtype))

##########################
if __name__ == "__main__":
    httpd = make_server(MSConfig.config.get('main','host'), int(MSConfig.config.get('main','port')), myapp)
    log.info("Serving HTTP at %s:%s...", MSConfig.config.get('main','host'), MSConfig.config.get('main','port'))
    try:
        httpd.serve_forever()
    except KeyboardInterrupt, err:
        log.info('Server gracefull shutdown')
    except Exception, err:
        log.error('Server fatal error: %s', str(err))
    finally:
        pass
